<template>
  <div style="padding: 20px">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px">
      <el-form-item label="店铺" prop="shopId">
        <el-select v-model="queryParams.storeIdList" multiple collapse-tags filterable clearable @keyup.enter.native="handleQuery" @change="clearStoreIdList()" placeholder="请选择店铺">
          <el-option v-for="item in storeMgmtList" :key="item.id" :label="item.storeAbbr" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="事业部" prop="divName">
        <el-select v-model="queryParams.divNameList" multiple collapse-tags filterable clearable @keyup.enter.native="handleQuery" @change="clearDivNameList()" placeholder="请选择事业部">
          <el-option v-for="item in divNameOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品标签" prop="shopId">
        <div v-for="(item, index) in queryParams.goodsLabelList" :key="index" style="float: left;">
          <el-input placeholder="请输入商品标签" v-model="queryParams.goodsLabelList[index]" @keyup.enter.native="handleQuery" @change="clearGoodsLabelList()" clearable style="float: left;width: calc(100% - 35px);"></el-input>
          <el-button type="danger" icon="el-icon-delete-solid" @click="queryParams.goodsLabelList.splice(index, 1)" circle style="float: right;margin-right: 3px;"></el-button>
        </div>
        <el-button type="primary" icon="el-icon-plus" @click="queryParams.goodsLabelList.push('')" circle style="float: left;margin-left: 3px;"></el-button>
      </el-form-item>
      <el-form-item label="负责人" prop="storeLeader">
        <el-select v-model="queryParams.storeLeaderList" multiple collapse-tags filterable clearable @keyup.enter.native="handleQuery" @change="clearStoreLeaderList()" placeholder="请选择负责人">
          <el-option v-for="item in leaderList" :key="item.userId" :label="item.nickName" :value="item.userId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上新日期" prop="shopId">
        <el-date-picker v-model="queryParams.time1" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @keyup.enter.native="handleQuery"></el-date-picker>
      </el-form-item>
      <el-form-item label="统计日期" prop="shopId">
        <el-date-picker v-model="queryParams.time2" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @keyup.enter.native="handleQuery"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button icon="el-icon-download" @click="handleExport">下载</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="toolbar">
      <el-col :span="24">
        <el-table v-loading="loading" :data="tableData" height="300" style="width: 100%">
          <el-table-column v-if="queryParams.storeIdList.length == 0 && queryParams.goodsLabelList.length == 0 && queryParams.storeLeaderList.length == 0 && queryParams.divNameList.length == 0" prop="store_name" label="店铺"></el-table-column>
          <el-table-column v-if="queryParams.storeIdList.length != 0" prop="store_name" label="店铺"></el-table-column>
          <el-table-column v-if="queryParams.goodsLabelList.length != 0" prop="goodsLabel" label="商品标签"></el-table-column>
          <el-table-column v-if="queryParams.storeLeaderList.length != 0" prop="store_leader" label="负责人"></el-table-column>
          <el-table-column v-if="queryParams.divNameList.length != 0" prop="div_name" label="事业部"></el-table-column>
          <el-table-column prop="count_500_plus" label="500以上"></el-table-column>
          <el-table-column prop="count_200_500" label="200-500"></el-table-column>
          <el-table-column prop="count_100_200" label="100-200"></el-table-column>
          <el-table-column prop="count_50_100" label="50-100"></el-table-column>
          <el-table-column prop="count_30_50" label="30-50"></el-table-column>
          <el-table-column prop="count_10_30" label="10-30"></el-table-column>
          <el-table-column prop="count_3_10" label="3-10"></el-table-column>
          <el-table-column prop="count_1_3" label="1-3"></el-table-column>
          <el-table-column prop="count_0" label="0"></el-table-column>
          <el-table-column prop="count_all" label="合计"></el-table-column>
          <el-table-column prop="salesTurnoverRate" label="动销率">
            <template slot-scope="scope">
              {{scope.row.salesTurnoverRate?scope.row.salesTurnoverRate:0}}%
            </template>
          </el-table-column>
          <el-table-column prop="salesTurnoverRateThree" label="动销率3">
            <template slot-scope="scope">
              {{scope.row.salesTurnoverRateThree?scope.row.salesTurnoverRateThree:0}}%
            </template>
          </el-table-column>
          <el-table-column prop="netSalesRevenue" label="净销售额">
            <template slot-scope="scope">
              {{divideAndFormat(scope.row.netSalesRevenue)}}万
            </template>
          </el-table-column>
          <el-table-column prop="promotionRatio" label="推广占比">
            <template slot-scope="scope">
              {{scope.row.promotionRatio?scope.row.promotionRatio:0}}%
            </template>
          </el-table-column>
          <el-table-column prop="customerOrderPrice" label="客单价">
            <template slot-scope="scope">
              {{scope.row.customerOrderPrice?scope.row.customerOrderPrice:0}}
            </template>
          </el-table-column>
          <el-table-column prop="dynamicSalesThree" label="动销3价值">
            <template slot-scope="scope">
              {{scope.row.dynamicSalesThree?scope.row.dynamicSalesThree:0}}
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="24">
        <div id="productTierDashboard" style="width: 100%;height: 380px;margin: 10px auto;"></div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {generateColors, line_bar_chart} from "@/utils/echartsOption";
import {getNormalStoreMgmtList, getProductEchelon, getStoreLeaderList} from "@/api/business/storeMgmt"
import {exportProductEchelon} from "@/api/business/goodsIndicators";
import {getConfigByType} from "@/api/business/operationStoreConfig";

export default {
  name: "ProductTierDashboard",
  components: {},
  data() {
    return {
      productTierDashboard: null,
      tableData: [],
      storeMgmtList: [],
      queryParams: {
        storeIdList: [],
        storeLeaderList: [],
        goodsLabelList: [],
        divNameList: [],
        time1: [],
        time2: [],
      },
      divNameOptions: [{
        value: '海报事业部',
        label: '海报事业部'
      }, {
        value: '3C事业部',
        label: '3C事业部'
      }],
      loading: false,
      leaderList: []
    }
  },
  created() {
    this.getNormalStoreMgmtList();
    this.getUserInfo();
    this.getStoreLeaderList();
  },
  mounted() {
    this.productTierDashboard = echarts.init(document.getElementById('productTierDashboard'))
    window.addEventListener('resize', () => {
      this.productTierDashboard.resize()
    })
    this.getProductTierDashboard()
  },
  methods: {
    getUserInfo(){
      getConfigByType({configType:2}).then(response => {
        if (response.data!==undefined){
          this.queryParams.storeIdList=response.data.configStore.split(",");
        }
      })
    },
    /** 查询店铺列表 */
    getNormalStoreMgmtList(){
      getNormalStoreMgmtList().then(res => {
        this.storeMgmtList = res.data
      })
    },
    getProductTierDashboard(){
      const _this = this;
      let data = [],xData = ['500以上', '200-500', '100-200', '50-100', '30-50', '10-30', '3-10', '1-3', '0', '合计'],legend = [],company = []
      this.tableData.map(i => {
        data.push({type: 0, fontColor: 'black', topLineLabel: 'top', data: [i.count_500_plus, i.count_200_500, i.count_100_200, i.count_50_100, i.count_30_50, i.count_10_30, i.count_3_10, i.count_1_3, i.count_0, i.count_all], topLine: true, name: i.store_name?i.store_name:i.goodsLabel?i.goodsLabel:i.store_leader})
        legend.push(i.store_name?i.store_name:i.goodsLabel?i.goodsLabel:i.store_leader)
        company.push('')
      })
      _this.productTierDashboard.clear();
      const option = line_bar_chart({legend: legend, xData: xData, data: data, company: company, color: generateColors(legend.length), type: 1, grid: ["50px", "7%", "0%", "4px"], dataZoom: xData.length>12, barWidth: '12px', fontColor: 'black', titleColor: 'black'})
      _this.productTierDashboard.setOption(option);
    },
    handleQuery(){
      let queryParams = { ...this.queryParams }
      if (queryParams.storeIdList.length === 0 && queryParams.goodsLabelList.length === 0 && queryParams.storeLeaderList.length === 0 && queryParams.divNameList.length == 0){
        this.$message.error('请选择店铺/事业部/商品标签/负责人！！！！');
        return false
      }
      this.loading = true

      if (queryParams.time1!==null&&queryParams.time1.length>0){
        queryParams.upNewDateStart = queryParams.time1[0]
        queryParams.upNewDateEnd = queryParams.time1[1]

        delete queryParams.time1
      }

      if (queryParams.time2!==null&&queryParams.time2.length>0){
        queryParams.statDateStart = queryParams.time2[0]
        queryParams.statDateEnd = queryParams.time2[1]

        delete queryParams.time2
      }

      getProductEchelon(queryParams).then(res => {
        if (queryParams.storeIdList.length !== 0){

          const idToNameMap = this.storeMgmtList.reduce((map, item) => {
            map[item.id] = item.storeAbbr;
            return map;
          }, {});

          this.tableData = this.queryParams.storeIdList.map(storeIdItem => {
            // 查找list中是否存在当前storeId
            const existingItem = res.data.find(item => item.id === storeIdItem);

            // 如果存在，则更新store_name并返回
            if (existingItem) {
              existingItem.store_name = idToNameMap[storeIdItem];
              return existingItem;
            } else {
              // 如果不存在，则创建一个新的项并返回
              return {
                count_200_500: 0,
                count_1_3: 0,
                count_3_10: 0,
                count_50_100: 0,
                count_500_plus: 0,
                count_100_200: 0,
                count_0: 0,
                count_10_30: 0,
                count_all: 0,
                store_name: idToNameMap[storeIdItem] || '未知',
                id: storeIdItem,
                count_30_50: 0
              };
            }
          });
        }else {
          this.tableData = res.data
        }
        this.getProductTierDashboard()
        this.loading = false
      })
    },
    clearStoreIdList(){
      this.queryParams.storeLeaderList = []
      this.queryParams.goodsLabelList = []
      this.queryParams.divNameList = []
    },
    clearStoreLeaderList(){
      this.queryParams.storeIdList = []
      this.queryParams.goodsLabelList = []
      this.queryParams.divNameList = []
    },
    clearGoodsLabelList(){
      this.queryParams.storeIdList = []
      this.queryParams.storeLeaderList = []
      this.queryParams.divNameList = []
    },
    clearDivNameList(){
      this.queryParams.storeIdList = []
      this.queryParams.storeLeaderList = []
      this.queryParams.goodsLabelList = []
    },
    resetQuery(){
      this.queryParams = {
        storeIdList: [],
          storeLeaderList: [],
          goodsLabelList: [],
        divNameList: [],
          time1: [],
          time2: []
      }
      this.$resetForm("queryParams");
      this.productTierDashboard.clear();
      this.tableData = []
    },
    divideAndFormat(number) {
      if (number){
        // 将数字除以10000
        let result = number / 10000;
        // 使用toFixed方法保留1位小数
        result = result.toFixed(2);
        // 将结果转换回数字（如果需要）
        // 注意：toFixed返回的是一个字符串，如果需要数字类型，可以使用parseFloat或Number
        result = parseFloat(result);
        return result;
      }else {
        return 0
      }
    },
    // 导出
    handleExport(){

      if (this.tableData.length === 0){
        this.$message.warning('请先查询后下载');
        return false
      }

      let queryParams = { ...this.queryParams }
      if (queryParams.storeIdList.length === 0 && queryParams.goodsLabelList.length === 0 && queryParams.storeLeaderList.length === 0 && queryParams.divNameList.length == 0){
        this.$message.error('请选择店铺/事业部/商品标签/负责人！！！！');
        return false
      }

      if (queryParams.time1!==null&&queryParams.time1.length>0){
        queryParams.upNewDateStart = queryParams.time1[0]
        queryParams.upNewDateEnd = queryParams.time1[1]

        delete queryParams.time1
      }

      if (queryParams.time2!==null&&queryParams.time2.length>0){
        queryParams.statDateStart = queryParams.time2[0]
        queryParams.statDateEnd = queryParams.time2[1]

        delete queryParams.time2
      }
      exportProductEchelon(queryParams)
    },
    /** 查询店铺负责人列表 */
    getStoreLeaderList(){
      getStoreLeaderList().then(res => {
        this.leaderList = res.data
      })
    },
  }
}
</script>

<style scoped>

</style>
